package com.tidc.seaserverservice.service.impl;

import com.tidc.seaservermapper.dao.RoleDao;
import com.tidc.seaservermapper.dao.UserDao;
import com.tidc.seaservermodel.dto.UserDto;
import com.tidc.seaservermodel.entity.Fres;
import com.tidc.seaservermodel.entity.User;
import com.tidc.seaservermodel.exception.TidcBadParent;
import com.tidc.seaservermodel.exception.TidcUnLogin;
import com.tidc.seaservermodel.properties.RoleProperties;
import com.tidc.seaservermodel.util.RedisUtil;
import com.tidc.seaservermodel.util.SpringUtil;
import com.tidc.seaservermodel.config.RedisConfig;
import com.tidc.seaserverservice.service.SupervisorUserService;
import com.tidc.seaserverservice.util.SendCodeUtil;
import com.tidc.seaserverservice.util.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * @author ：冯涛滔
 * @date ：Created in 2020/9/12 9:35
 * @description：
 * @modified By：
 * @version:
 */
@Service
@Slf4j
public class SupervisorUserServiceImpl implements SupervisorUserService {
    @Resource
    private UserDao userDao;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private RoleDao roleDao;
    @Resource
    private RoleProperties roleProperties;
    @Resource
    private UserUtil userUtil;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private SendCodeUtil sendCodeUtil;
    @Override
    @Transactional(rollbackFor = {SQLException.class,TidcBadParent.class})
    public Fres<String> secondaryUser(User user) throws SQLException, TidcBadParent {
        Fres<String> fres = Fres.Success();
//        if(redisUtil.checkCode(RedisConfig.ADD_SECONDARY_CODE + user.getPhone(),user.getCode())){
            boolean repetition = userUtil.checkUserRepetition(user.getUsername(), user.getPhone());
            if(!repetition){
                user.setPassword(passwordEncoder.encode(user.getPassword()));
                user.setTypeClassify(2);
                userDao.insert(user);
                int roleInsert = roleDao.grantedToUserRole(user.getId(), roleProperties.getSecondaryUserRoleIds());
                if(roleInsert<1){
                    log.error("注册一个二级用户时插入角色失败了 user {}",user);
                    throw new SQLException("插入角色失败");
                }
            }else{
                fres = Fres.badRequestParent(null,"账号名或手机号已被注册");
            }
//        }else{
//            fres = Fres.badRequestParent(null,"验证码错误");
//        }
        return fres;
    }



    @Transactional(rollbackFor = {TidcBadParent.class})
    @Override
    public Fres<String> updateSecondaryUser(User user, Authentication authentication) throws TidcBadParent {
//        if(StringUtils.isEmpty(user.getPhone())  || redisUtil.checkCode(RedisConfig.PUT_SECONDARY_CODE + user.getPhone(),user.getCode())){
            user.setSuperiorUserId(Integer.valueOf(authentication.getName()));
            if(user.getPassword()!=null && !user.getPassword().equals("")){
                user.setPassword(passwordEncoder.encode(user.getPassword()));
            }
            int i = userDao.updateSecondaryUser(user);
            if(i<1){
                log.error("修改一个二级用户信息时失败了 user {}",user);
                throw new TidcBadParent("修改失败");
            }
            return Fres.Success();

//        }else{
//            return Fres.badRequestParent(null,"验证码错误");
//        }
    }
    @Override
    public Fres<User> getUserInfo(Authentication authentication) throws TidcUnLogin {
        Fres<User> fres = null;
        User user = userDao.queryById(Integer.valueOf(authentication.getName()));
        if (user!=null) {
            fres = Fres.Success(user,"");
        }else {
            log.error("尝试获取id为 {} 的用户失败",authentication.getName());
            fres = Fres.unLogin(null,"请重新登入");
        }
        return fres;
    }

    @Override
    public Fres<Map<Object, Object>> getSecondaryUserList(String query, int pageSize,int pageNum,Authentication authentication) throws TidcBadParent {
        int count = userDao.getSecondaryUserCount(query, Integer.parseInt(authentication.getName()));
        Map<Object, Object> map = SpringUtil.pagingPrepare(pageSize, pageNum, count);
        List<User> secondaryUserList = userDao.getSecondaryUserList(query,(pageNum - 1) * pageSize, pageSize,Integer.parseInt(authentication.getName())
        );
        map.put("userList",secondaryUserList);
        return Fres.Success(map,"成功");
    }

    @Override
    public Fres<Boolean> checkUserRepetition(String username,String phone) {
        int i = userDao.findingDuplicateByUsernameAndPhone(username, phone);
        return Fres.Success(i > 0, "查询完成");
    }

    @Override
    public Fres<User> getChildUser(Authentication authentication, int id) {
        User user = userDao.getChildUser(id, Integer.parseInt(authentication.getName()));
        Fres<User> fres = Fres.Success(user,"查询成功");
        if(user==null){
            fres = Fres.badRequestParent(null,"账号不存在");
        }

        return fres;
    }

    @Override
    public Fres<Map<Object, Object>> getSecondaryUserTaskInfoList(String query,int pageSize, int pageNum, Authentication authentication) throws TidcBadParent {
        int count = userDao.getSecondaryUserCount(query,Integer.parseInt(authentication.getName()));
        Map<Object, Object> map = SpringUtil.pagingPrepare(pageSize, pageNum, count);
        List<UserDto> list = userDao.getChildTaskInfoList(query, Integer.parseInt(authentication.getName()), (pageNum - 1) * pageSize, pageSize);
        map.put("list",list);
        return Fres.Success(map,"成功");
    }


}
